package com.lc.rongzecaifu.ui;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;

import com.lc.rongzecaifu.MyApplication;
import com.lc.rongzecaifu.activity.BankcardAddActivity;
import com.lc.rongzecaifu.activity.BaseActivity;
import com.lc.rongzecaifu.activity.ChoseBankActivity;
import com.lc.rongzecaifu.activity.WithdrawOrRechargeRecordActivity;
import com.lc.rongzecaifu.conn.JsonAccessToken;
import com.lc.rongzecaifu.conn.JsonBanklist;
import com.lc.rongzecaifu.rongzecaifu.R;
import com.zcx.helper.bound.BoundView;
import com.zcx.helper.bound.BoundViewHelper;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.util.UtilToast;

import java.math.BigDecimal;
import java.text.DecimalFormat;

import cn.trinea.android.common.util.ToastUtils;

/**
 * Created by Administrator on 2017/3/20.
 */
public class RechargeActivity extends BaseActivity implements View.OnClickListener {

    @BoundView(R.id.recharge_bank_ll) private LinearLayout recharge_bank_ll;
    @BoundView(R.id.recharge_bank_logo_iv) private SimpleDraweeView recharge_bank_logo_iv;
    @BoundView(R.id.recharge_bank_name_tv) private TextView recharge_bank_name_tv;
    @BoundView(R.id.recharge_bank_num_tv) private TextView recharge_bank_num_tv;
    @BoundView(R.id.recharge_bank_add_ll) private LinearLayout recharge_bank_add_ll;
    @BoundView(R.id.recharge_balance_tv) private TextView recharge_balance_tv;
    @BoundView(R.id.recharge_title_right_tv) private TextView recharge_title_right_tv;
    @BoundView(R.id.recharge_money_et) private EditText recharge_money_et;
    @BoundView(R.id.recharge_bt) private Button recharge_bt;

    private String bank_num = "";
    private PopupWindow popWindow;
    private String money;

    private void getBankListAccessToken() {

        new JsonAccessToken("user/banklist", new AsyCallBack<JsonAccessToken.Info>() {

            @Override
            public void onSuccess(String toast, int type, JsonAccessToken.Info info) throws Exception {

                new JsonBanklist(info.access_token, MyApplication.myPreferences.readUid(), new AsyCallBack<JsonBanklist.Info>() {
                    @Override
                    public void onSuccess(String toast, int type, JsonBanklist.Info info) throws Exception {

                        if (info != null) {
                            recharge_bank_ll.setVisibility(View.VISIBLE);
                            recharge_bank_name_tv.setText(info.list.get(0).bank_name);
                            bank_num = info.list.get(0).id;
                            recharge_bank_logo_iv.setImageURI(Uri.parse(info.list.get(0).bank_ico));
                            String string = info.list.get(0).bank_num;
                            String str2 = string.substring(string.length() - 4, string.length());
                            recharge_bank_num_tv.setText("（" + " 尾号 " + str2 + " " + "）");

                            Log.d("Recharge_bank_name", info.list.get(0).bank_name + "");


                        } else {

                            UtilToast.show(RechargeActivity.this, JsonBanklist.TOAST);
                        }

                    }

                    @Override
                    public void onFail(String toast, int type) throws Exception {

                        recharge_bank_ll.setVisibility(View.GONE);

                    }

                }).execute(RechargeActivity.this, true);

            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);

                UtilToast.show(RechargeActivity.this, "安全验证失败！");
            }

        }).execute(this, true);

    }

    private void getRechargeAccessToken(final String money) {
/*
        new JsonAccessToken("pay/charge", new AsyCallBack<JsonAccessToken.Info>() {
            @Override
            public void onSuccess(String toast, int type, JsonAccessToken.Info info) throws Exception {

                // String url = "https://www.haiying365.com/api/pay/charge?uid=" + MyApplication.myPreferences.readUid() + "&money=" + money + "&way=ecpss2" + "&access_token=" + info.access_token;
                //https://open.fuiou.com/gateway/appDocList.do
                    //                initWithPayvalidate(info.access_token);
                     *//*   String url = " http://www-1.fuiou.com:18670/mobile_pay/update/receiveSDK.pay";

                        wv01.loadUrl(url);*//*
                //  String url = " http://www-1.fuiou.com:18670/mobile_pay/update/receiveSDK.pay?uid=" + MyApplication.myPreferences.readUid() + "&money=" + money + "&way=ecpss2" + "&access_token=" + info.access_token;
                // String url = "https://open.fuiou.com/gateway/appDocList.do/api/pay/charge?uid=" + MyApplication.myPreferences.readUid() + "&money=" + money + "&way=ecpss2" + "&access_token=" + info.access_token;


                new JsonWithPay(info.access_token, MyApplication.myPreferences.readUid(), recharge_money_et.getText().toString(), bank_num, "fuyou_sdk", new AsyCallBack<JsonWithPay.Info>() {

                    @Override
                    public void onSuccess(String toast, int type, JsonWithPay.Info info) throws Exception {
//
                            Bundle bundle = new Bundle();

                            bundle.putString(AppConfig.MCHNT_CD, info.submitdata.MCHNTCD);
                            bundle.putString(AppConfig.MCHNT_AMT, info.submitdata.AMT);
                            bundle.putString(AppConfig.MCHNT_BACK_URL, info.submitdata.BACKURL);
                            bundle.putString(AppConfig.MCHNT_BANK_NUMBER, info.submitdata.BANKCARD);
                            bundle.putString(AppConfig.MCHNT_ORDER_ID, info.submitdata.MCHNTORDERID);
                            bundle.putString(AppConfig.MCHNT_USER_IDCARD_TYPE, info.submitdata.IDTYPE);
                            bundle.putString(AppConfig.MCHNT_USER_ID, info.submitdata.USERID);
                            bundle.putString(AppConfig.MCHNT_USER_IDNU, info.submitdata.IDNO);
                            bundle.putString(AppConfig.MCHNT_USER_NAME, info.submitdata.NAME);
                            bundle.putString(AppConfig.MCHNT_SING_KEY, info.submitdata.SIGN);
                            bundle.putString(AppConfig.MCHNT_SDK_SIGNTP, info.submitdata.SIGNTP);
                            bundle.putString(AppConfig.MCHNT_SDK_TYPE, info.submitdata.TYPE);
                            bundle.putString(AppConfig.MCHNT_SDK_VERSION, info.submitdata.VERSION);

                            int i = FyPay.pay(RechargeActivity.this, bundle, new FyPayCallBack() {
                                @Override
                                public void onPayComplete(String arg0, String arg1, Bundle arg2) {
                                    // TODO Auto-generated method stub

                                    Toast.makeText(RechargeActivity.this, arg0 + "  " +arg1, Toast.LENGTH_SHORT).show();

                                    String url = " http://www-1.fuiou.com:18670/mobile_pay/update/receiveSDK.pay";

                                }

                                @Override
                                public void onPayBackMessage(String arg0) {
                                    // TODO Auto-generated method stub
                                }

                                @Override
                                protected Object clone() throws CloneNotSupportedException {
                                    return super.clone();

                                }
                            });

                            Log.d(i + "", "adslkfffffffffffffffffffffff");

                            popWindow.dismiss();

                    }

                    @Override
                    public void onFail(String toast, int type) throws Exception {

                        Toast.makeText(RechargeActivity.this, toast, Toast.LENGTH_SHORT).show();

                    }

                }).execute(RechargeActivity.this, true);


            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
                UtilToast.show(RechargeActivity.this, "安全验证失败！");
            }
        }).execute(this, true);*/

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_recharge);

        recharge_title_right_tv.setOnClickListener(this);
        recharge_bank_ll.setOnClickListener(this);
        recharge_bank_add_ll.setOnClickListener(this);
        recharge_bt.setOnClickListener(this);



        getBankListAccessToken();

        recharge_balance_tv.setText(MyApplication.myPreferences.readAccount_money() + "元");

    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {

            case R.id.recharge_title_right_tv:

                startActivity(new Intent(this, WithdrawOrRechargeRecordActivity.class).putExtra("mode", false));//true为提现，false为充值
                break;

            case R.id.recharge_bank_ll:

                startActivityForResult(new Intent(this, ChoseBankActivity.class), 1);

                break;

            case R.id.recharge_bank_add_ll:

                if (MyApplication.myPreferences.readId_status().equals("0")) {

                    ToastUtils.show(this, "请先通过实名认证，实名认证通过后方可绑定银行卡。");

                } else if (MyApplication.myPreferences.readId_status().equals("2")) {

                    ToastUtils.show(this, "实名认证审核中，实名认证通过后方可绑定银行卡。");

                } else if (MyApplication.myPreferences.readId_status().equals("1")) {

                    startActivity(new Intent(this, BankcardAddActivity.class));

                }

                break;

            case R.id.recharge_bt:

                money = recharge_money_et.getText().toString().replaceAll(" ", "");

                if (TextUtils.isEmpty(money)) {
                    ToastUtils.show(this, "请输入充值金额！");
                } else if ((money.contains(".") && Double.parseDouble(money) < 100) || (!money.contains(".") && Long.parseLong(money) < 100)) {
                    ToastUtils.show(this, "请输入大于100元的金额！");
                } else {

                    showPopupWindow(view);

                }

                break;

        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK && requestCode == 1) {

            recharge_bank_name_tv.setText(data.getStringExtra("name"));

            recharge_bank_logo_iv.setImageURI(Uri.parse(data.getStringExtra("ico")));

            String string = data.getStringExtra("num");

            String str2 = string.substring(string.length() - 4, string.length());

            recharge_bank_num_tv.setText("（" + " 尾号 " + str2 + " " + "）");

            bank_num = data.getStringExtra("id");
        }
    }

    private void showPopupWindow(View parent) {

        if (popWindow == null) {

            View view = BoundViewHelper.boundView(this, MyApplication.scaleScreenHelper.loadView((ViewGroup) LayoutInflater.from(this)
                    .inflate(R.layout.dialog_03, null)));
            //LayoutParams相当于一个Layout的信息包，它封装了Layout的位置、高、宽等信息。
            popWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            initPop(view);
        }
        //设置动画效果
        popWindow.setAnimationStyle(android.R.style.Animation_Dialog);
        //获取popwindow焦点
        popWindow.setFocusable(true);
        //设置popwindow如果点击外面区域，便关闭。
        popWindow.setOutsideTouchable(true);
        popWindow.setBackgroundDrawable(new BitmapDrawable());
        //实现软键盘不自动弹出,ADJUST_RESIZE属性表示Activity的主窗口总是会被调整大小，从而保证软键盘显示空间。
        popWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置popwindow显示位置
        popWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
    }

    public void initPop(View view) {
        TextView tv01 = (TextView) view.findViewById(R.id.dl_tv_01);// 取消
        TextView tv02 = (TextView) view.findViewById(R.id.dl_tv_02);// 确定

        TextView text_moneycount = (TextView) view.findViewById(R.id.text_moneycount);

        text_moneycount.setText(money);

        tv01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                popWindow.dismiss();
            }
        });

        tv02.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {

                DecimalFormat decimalFormat = new DecimalFormat("#.00");

//                Log.e("---", "money" + money +"format" + decimalFormat.format(new BigDecimal(money)));

                getRechargeAccessToken(decimalFormat.format(new BigDecimal(money)));

            }
        });
    }

}
